<template>
  <div class="device-list">
    <div class="header">
      <el-input
        v-model="keyword"
        placeholder="搜索设备"
        class="search"
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleAdd">
        添加设备
      </el-button>
    </div>

    <el-table :data="devices" v-loading="loading">
      <el-table-column prop="name" label="设备名称" />
      <el-table-column prop="type" label="设备类型" />
      <el-table-column prop="location" label="位置" />
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-switch
            v-model="row.status"
            @change="handleStatusChange(row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button link type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :title="form.id ? '编辑设备' : '添加设备'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form :model="form" label-width="100px">
        <el-form-item label="设备名称" required>
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="设备类型" required>
          <el-input v-model="form.type" />
        </el-form-item>
        <el-form-item label="位置">
          <el-input v-model="form.location" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useLoadingStore } from '@/stores/loading'
import {
  getDeviceList,
  createDevice,
  updateDevice,
  deleteDevice,
  searchDevices
} from '@/api/device'

const loadingStore = useLoadingStore()
const devices = ref([])
const loading = ref(false)
const keyword = ref('')
const dialogVisible = ref(false)
const form = ref({
  name: '',
  type: '',
  location: '',
  status: false
})

const loadDevices = async () => {
  loadingStore.setLoading(true)
  try {
    console.log('开始加载设备列表...')
    const res = await getDeviceList()
    console.log('设备列表数据:', res)
    if (Array.isArray(res)) {
      devices.value = res
    } else {
      console.error('返回数据格式错误:', res)
      ElMessage.error('数据格式错误')
    }
  } catch (error) {
    console.error('加载设备列表失败:', error)
    ElMessage.error(error.message || '加载设备列表失败')
  } finally {
    loadingStore.setLoading(false)
  }
}

const handleSearch = async () => {
  if (keyword.value) {
    devices.value = await searchDevices(keyword.value)
  } else {
    await loadDevices()
  }
}

const handleAdd = () => {
  form.value = {
    name: '',
    type: '',
    location: '',
    status: false
  }
  dialogVisible.value = true
}

const handleEdit = (row) => {
  form.value = { ...row }
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该设备吗？')
    await deleteDevice(row.id)
    ElMessage.success('删除成功')
    await loadDevices()
  } catch (e) {
    if (e !== 'cancel') {
      console.error(e)
    }
  }
}

const handleStatusChange = async (row) => {
  try {
    await updateDevice(row.id, row)
    ElMessage.success('状态更新成功')
  } catch (e) {
    row.status = !row.status
  }
}

const handleSubmit = async () => {
  try {
    if (form.value.id) {
      await updateDevice(form.value.id, form.value)
      ElMessage.success('更新成功')
    } else {
      await createDevice(form.value)
      ElMessage.success('添加成功')
    }
    dialogVisible.value = false
    await loadDevices()
  } catch (e) {
    console.error(e)
  }
}

onMounted(() => {
  loadDevices()
})
</script>

<style lang="scss" scoped>
.device-list {
  .header {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .search {
      width: 300px;
    }
  }
}
</style> 